package com.ruoyi.xqsp.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quyang.voice.utils.StringUtils;
import com.ruoyi.common.utils.status.ResponseUtil;
import com.ruoyi.xqsp.domain.SpConsumeRecord;
import com.ruoyi.xqsp.domain.SpUsers;
import com.ruoyi.xqsp.domain.entity.MemberConvert;
import com.ruoyi.xqsp.domain.entity.RechargeRecord;
import com.ruoyi.xqsp.domain.entity.UserMemberRecord;
import com.ruoyi.xqsp.domain.entity.UserRecord;
import com.ruoyi.xqsp.service.*;
import com.ruoyi.xqsp.utils.TokenServices;
import com.ruoyi.xqsp.utils.XqidUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.xqsp.domain.SpRechargeRecord;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 充值管理Controller
 *
 * @author ruoyi
 * @date 2021-05-07
 */
@RestController
@RequestMapping("/xqsp/record")
public class SpRechargeRecordController extends BaseController {
    @Autowired
    private ISpRechargeRecordService spRechargeRecordService;
    @Autowired
    private ISpUsersService spUsersService;
    @Autowired
    private ISpKeyService spKeyService;
    @Autowired
    private ISpCarmichaelService spCarmichaelService;
    @Autowired
    private ISpMemberMoneyService spMemberMoneyService;

    @Autowired
    SpConsumeRecordService consumeRecordService;


    @Autowired
    TokenServices tokenServices;

    /**
     * 查询充值管理列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpRechargeRecord spRechargeRecord) {
        startPage();
        List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordList(spRechargeRecord);
        TableDataInfo dataTable = getDataTable(list);
        List<UserRecord> userRecordList = new ArrayList<>();
        UserRecord userRecord;

        for (SpRechargeRecord record : list) {
            userRecord = new UserRecord();
            userRecord.setSpRechargeRecord(record);
            if (record.getUserId() != null) {
                if (spUsersService.selectSpUsersById(record.getUserId()) != null) {
                    userRecord.setUserName(spUsersService.selectSpUsersById(record.getUserId()).getUserName());
                }
            }

            userRecordList.add(userRecord);
        }
        dataTable.setRows(userRecordList);
        return dataTable;
    }

    /**
     * 导出充值管理列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:record:export')")
    @Log(title = "充值管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpRechargeRecord spRechargeRecord) {
        List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordList(spRechargeRecord);
        ExcelUtil<SpRechargeRecord> util = new ExcelUtil<SpRechargeRecord>(SpRechargeRecord.class);
        return util.exportExcel(list, "record");
    }

    /**
     * 获取充值管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:record:query')")
    @GetMapping(value = "/{rechargeRecordId}")
    public AjaxResult getInfo(@PathVariable("rechargeRecordId") Long rechargeRecordId) {
        return AjaxResult.success(spRechargeRecordService.selectSpRechargeRecordById(rechargeRecordId));
    }

    /**
     * 新增充值管理
     */

    @Log(title = "充值管理", businessType = BusinessType.INSERT)
    @PostMapping("/addRechargeRecord")
    public AjaxResult addRechargeRecord(@RequestBody SpRechargeRecord spRechargeRecord) {
        String rechargeRecordOrder;

        boolean bHave = true;
        while (bHave) {
            rechargeRecordOrder = XqidUtils.UserRecord();
            if (spRechargeRecordService.selectSpRechargeRecordByOrder(rechargeRecordOrder) == null) {
                bHave = false;
                spRechargeRecord.setRechargeRecordOrder(rechargeRecordOrder);
            }
        }
        spRechargeRecord.setRechargeRecordTime(new Date());
        Long days;
        if (spRechargeRecord.getRechargeRecordType() == 1) {//VIP月卡
            days = 30l;
            spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
            return toAjax(spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord));
        }
        if (spRechargeRecord.getRechargeRecordType() == 2) {//VIP季卡
            days = 90l;
            spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
            return toAjax(spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord));
        }
        if (spRechargeRecord.getRechargeRecordType() == 8) {//VIP半年卡
            days = 180l;
            spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
            return toAjax(spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord));
        }
        if (spRechargeRecord.getRechargeRecordType() == 3) {//VIP年卡
            days = 360l;
            spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
            return toAjax(spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord));
        }
        if (spRechargeRecord.getRechargeRecordType() == 7) {//金币充值
            Long glod = spRechargeRecord.getRechargeRecordMoney();
            spUsersService.updatGlodByUserId(spRechargeRecord.getUserId(), glod);
            return toAjax(spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord));
        }

        return AjaxResult.error("未知错误");
    }

    /**
     * 修改充值管理
     */
    @PreAuthorize("@ss.hasPermi('xqsp:record:edit')")
    @Log(title = "充值管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpRechargeRecord spRechargeRecord) {
        return toAjax(spRechargeRecordService.updateSpRechargeRecord(spRechargeRecord));
    }

    /**
     * 删除充值管理
     */
    @PreAuthorize("@ss.hasPermi('xqsp:record:remove')")
    @Log(title = "充值管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{rechargeRecordIds}")
    public AjaxResult remove(@PathVariable Long[] rechargeRecordIds) {
        return toAjax(spRechargeRecordService.deleteSpRechargeRecordByIds(rechargeRecordIds));
    }

    /**
     * 前台充值记录查询
     *
     * @param rechargeRecord
     * @return
     */
    @PostMapping("/getAll")
    public TableDataInfo getAll(@RequestBody RechargeRecord rechargeRecord) {
        startPages(rechargeRecord.getPageNums(), rechargeRecord.getPageSize());
        if (rechargeRecord.getRechargeRecordWay() == 0) {
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordListsBySelfAndKeFu(rechargeRecord.getUserId());
            return getDataTable(list);
        } else if (rechargeRecord.getRechargeRecordWay() == 1) {
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordLists(rechargeRecord.getUserId());
            return getDataTable(list);
        } else if (rechargeRecord.getRechargeRecordWay() == 2) {
            SpRechargeRecord spRechargeRecord = new SpRechargeRecord();
            spRechargeRecord.setUserId(rechargeRecord.getUserId());
//            spRechargeRecord.setRechargeRecordWay(rechargeRecord.getRechargeRecordWay());
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordList(spRechargeRecord);
            return getDataTable(list);

        }
        return getDataTables();

    }

    /**
     * 会员福利兑换
     *
     * @param memberConvert
     * @return
     */
    @PostMapping("/addRecord")
    @Transactional
    public ResponseUtil addRecord(MemberConvert memberConvert, HttpServletRequest request) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("recharge_record_order",memberConvert.getCode());
        wrapper.eq("recharge_record_state",0);
        SpRechargeRecord spRechargeRecord = spRechargeRecordService.getOne(wrapper);

        if (spRechargeRecord == null){
            return ResponseUtil.fail("兑换码无效");
        }
        SpUsers user = tokenServices.getUser(request);
        spRechargeRecord.setRechargeRecordState(1);
        spRechargeRecordService.updateById(spRechargeRecord);
        SpUsers spUsers = spUsersService.getById(user.getUserId());

        if (spUsers!= null && spUsers.getUserMembersDay() != null){
            if ( spUsers.getUserMembersDay().compareTo(new Date()) > 0){
                spUsers.setUserMembersDay(DateUtil.offsetDay(spUsers.getUserMembersDay(),spRechargeRecord.getRechargeRecordNumber().intValue()));
            }else {
                spUsers.setUserVipType(0);
                spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),spRechargeRecord.getRechargeRecordNumber().intValue()));
            }
        }
        spUsersService.updateById(spUsers);
//        spUsersService.updatMembersDayByUserId(user.getUserId(),spRechargeRecord.getRechargeRecordNumber());





        SpConsumeRecord consumeRecord = new SpConsumeRecord();
        consumeRecord.setMoney(BigDecimal.valueOf(spRechargeRecord.getRechargeRecordNumber()));
        consumeRecord.setTradeNo(StringUtils.generateOrderNumber());
        consumeRecord.setPayType(2);
        consumeRecord.setUserId(user.getUserId());
        consumeRecord.setCurrentBalance(user.getUserGlod());
        consumeRecord.setChangeType(2);
        consumeRecord.setType(6);
        consumeRecord.setCreateTime(new Date());
        consumeRecord.setDescs("兑换会员");
        consumeRecordService.save(consumeRecord);

        return ResponseUtil.success();
    }

    /**
     * 会员记录查询
     * @return
     */

    @PostMapping("/getAllMem")
    public TableDataInfo getAllMem(@RequestBody UserMemberRecord userMemberRecord) {
        startPages(userMemberRecord.getPageNums(), userMemberRecord.getPageSize());
        if (userMemberRecord.getType() == 1) {//查询所有
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordListById(userMemberRecord.getUserId());
            return getDataTable(list);
        }
        if (userMemberRecord.getType() == 2) {//推广奖励
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordListById1(userMemberRecord.getUserId());
            return getDataTable(list);
        }
        if (userMemberRecord.getType() == 3) {//会员购买
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordListById2(userMemberRecord.getUserId());
            return getDataTable(list);
        }
        if (userMemberRecord.getType() == 4) {
            List<SpRechargeRecord> list = spRechargeRecordService.selectSpRechargeRecordListById3(userMemberRecord.getUserId());
            return getDataTable(list);
        }
        return getDataTables();
    }
//
//    /**
//     * 金币充值会员
//     *
//     * @param spRechargeRecord
//     * @return
//     */
//    @PostMapping("/payByGlod")
//    public AjaxResult payByGlod(@RequestBody SpRechargeRecord spRechargeRecord) {
//
//        spRechargeRecord.setRechargeRecordMoney(spMemberMoneyService.selectSpMemberMoneyById(spRechargeRecord.getMoneyType()).getMemberMoneyNumber());
//        String rechargeRecordOrder;
//
//        boolean bHave = true;
//        while (bHave) {
//            rechargeRecordOrder = XqidUtils.UserRecord();
//            if (spRechargeRecordService.selectSpRechargeRecordByOrder(rechargeRecordOrder) == null) {
//                bHave = false;
//                spRechargeRecord.setRechargeRecordOrder(rechargeRecordOrder);
//            }
//        }
//        spRechargeRecord.setRechargeRecordTime(new Date());
//        spRechargeRecord.setRechargeRecordWay(1l);
//        SpUsers users = spUsersService.selectSpUsersById(spRechargeRecord.getUserId());
//        if (users == null)
//            return AjaxResult.error1("找不到用户信息");
//
//        if (users.getUserGlod().compareTo(spRechargeRecord.getRechargeRecordMoney()) ) {
//            spUsersService.updateUserGlod(spRechargeRecord.getUserId(), spRechargeRecord.getRechargeRecordMoney());
//            spRechargeRecord.setRechargeRecordState(1);
//            Long days;
//            if (spRechargeRecord.getRechargeRecordType() == 1) {//VIP月卡
//                days = 30l;
//                spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
//            }
//            if (spRechargeRecord.getRechargeRecordType() == 2) {//VIP季卡
//                days = 90l;
//                spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
//            }
//            if (spRechargeRecord.getRechargeRecordType() == 8) {//VIP半年卡
//                days = 180l;
//                spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
//                if (users.getUserVipType() < 1)
//                    users.setUserVipType(1);
//                spUsersService.updateSpUsers(users);
//            }
//            if (spRechargeRecord.getRechargeRecordType() == 3) {//VIP年卡
//                days = 360l;
//                spUsersService.updatMembersDayByUserId(spRechargeRecord.getUserId(), days);
//                if (users.getUserVipType() < 2)
//                    users.setUserVipType(2);
//                spUsersService.updateSpUsers(users);
//            }
//            spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord);
//            return AjaxResult.success("购买成功");
//        } else {
//            return AjaxResult.error1("金币不足");
//        }
//
//
//    }

    public static void main(String[] args) {



        for (int i = 0; i < 10; i++) {
            String s = RandomStringUtils.randomAlphanumeric(12);
            System.out.println(s);
        }


    }

}
